<template>
  <div
    class="_row g-flex v-attribute-list-property"
    :class="{_selected:selected}"
    @click="handleSelectRow" >
    <div
      v-if="!isPropertyGroup"
      class="_col-label"
      :title="config.tips"
      :style="{'flex-basis': largeType ? '120px' : '100px' }"
      style="display: flex; align-items: center;">
      <span 
        style="display: inline-block; width: 100%; overflow: hidden;text-overflow: ellipsis;
            white-space: nowrap;">
        {{config.name}}
      </span>
    </div>
    <div class="_col-value g-relative" :data-value-type="config.editType">

      <template v-if="config.editType==='input' || config.editType==='textarea'">
        <m-simple-input
          ref="input"
          v-model="valueForEdit"
          :readonly="readonly"
          :class="readonly ? '_readonly':''"
          :type="config.editType"
          @focus="handleFocusRow($event)"
          @blur="handleSaveInput"
        />
      </template>
      <template v-else-if="config.editType==='switch'">
        <a-checkbox :checked="value" :disabled="readonly" @change="handleCheckChange">
          {{value }}
        </a-checkbox>

      </template>
      <template v-else-if="config.editType==='single-select'">
        <a-select v-model="valueForEdit" :style="{width:isPropertyGroup ? '100px' : '164px'}" :disabled="readonly" @change="handleSingleSelectChange">
          <a-select-option
            v-for=" (item,index) in property.config.items || []"
            :key="index"
            :value="item.value"
            :title="item.label"
          >
            {{item.label}}
          </a-select-option>
        </a-select>
        <!-- <div v-for="(it,index) in property.rowData.value" :key="index">{{it.value}}</div> -->
      </template>
      <template v-else-if="config.editType==='muti-select'">
        <a-select v-model="valueForEdit"  @change="handleMultiSelectChange">
          <a-select-option
            v-for=" (item,index) in property.options || []"
            :key="index"
            :value="item.value"
            :title="item.label"
          >
            {{item.label}}
          </a-select-option>
        </a-select>
        <div v-for="(it,index) in valueForEdit" :key="index">{{it.value}}</div>
      </template>
      <template v-else-if="config.editType==='tree-single-select'">

        <span v-if="value" class="g-inline-block">
          <img v-if="iconPath" style="margin-top:-3px;width: 16px;height: 16px;" :src="iconPath"/>
          {{ getDisplayText(value) }}
        </span>
        <span v-if="!readonly && selected" class="_img-btn" style="position:absolute;top:6px;right:4px;margin-left:14px" @click="handleSingleSelect">
          <img style="height:14px;width:14px" src='statics/icons/app/iconmore.png'>
        </span>

      </template>
      <template v-else-if="config.editType==='tree-muti-select'">
        <div  style="padding-right:24px">
          <div v-for="(it,index) in value||[]" :key="index" class="tree-muti-select-box">
            <img v-if="getIconPath(it)" :src="getIconPath(it)"/>
            <span class="g-m-lr-6"> {{ getDisplayText(it) }}</span>
            <img
              v-if="!readonly"
              class="_img-btn delete-btn"
              src="statics/icons/app/icondelete2.png"
              style="height:16px;width:16px;"
              @click="deleteTreeItem(index)"/>
          </div>
        </div>
        <span v-if="!readonly && selected" class="_img-btn" style="position:absolute;top:6px;right:4px" @click="handleMultiSelect">
          <img style="height:14px;width:14px" src='statics/icons/app/iconadd3.png' >
        </span>
      </template>
      <template v-else-if="config.editType==='compounded-input'" >
        <m-compounded-input
          :type="type"
          :value="valueForEdit"
          :row="property"
          @change="handleCompoundChange"
        />

      </template>
      <template v-if="config.editType==='muti-row-input' ">
        <div>
          <div class="g-m-r-20" style="border-right:1px solid #E4E3E3">
            <div
              v-for="(item,index) in mutiRowInputValues"
              :key="index"
              class="g-relative g-flex g-flex-1 _textarea" 
            >
              <m-simple-input
                :value="item"
                :readonly="readonly"
                :class="readonly ? '_readonly':''"
                :height="'30px'"
                style="margin-right:10px;padding-left:5px;padding-top:5px;padding-bottom:5px"
                type="textarea"
                @blur="handleMultiRowSaveInput(index)"
                @input="value => handleMultiRowInputChange(value, index)"
              />
              <span v-if="!readonly && selected" class="_img-btn" style="position:absolute;top:8px;right:4px;height:16px" @click="handleMultiRowDelete(index)">
                <img style="height:12px;width:12px" src='statics/icons/app/icondelete2.png'>
              </span>
            </div>
          </div>
          <span v-if="!readonly && selected" class="_img-btn" style="position:absolute;top:6px;right:4px" @click="handlePopMultiRowInput">
            <img style="height:14px;width:14px" src='statics/icons/app/iconadd3.png'>
          </span>
        </div>
      </template>

      <template v-if="config.editType==='muti-row-text'">
        <div>
          <div class="g-m-r-20">
            <div 
              v-for="(item,index) in (value && value.toArray())" 
              :key="index" 
              class="g-relative g-flex g-flex-1" 
              style="justify-content: space-between; align-items: center; height: 20px">
              <span class="g-inline-block" style="padding-right:14px">{{item}}</span>             
            </div>
          </div>
          <!-- <span v-if="!readonly && selected && (value && value.toArray().length > 0)" class="_img-btn" style="position:absolute;top:50%;right:22px;transform: translateY(-50%)" @click="handleMultiRowTextDelete">
            <img style="height:12px;width:12px" src='statics/icons/app/icondelete2.png'>
          </span> -->
          <span v-if="!readonly && selected" class="_img-btn" style="position:absolute;top:6px;right:4px" @click="handlePopMultiRowText">
            <img style="height:14px;width:14px" src='statics/icons/app/iconadd3.png'>
          </span>
        </div>
      </template>
      <template v-if="config.editType === 'img' ">
        <img :src="imageURL" alt="" width="16px" style="margin-bottom: 2px">
        <span v-if="!readonly && selected" class="_img-btn" style="position:absolute;top:6px;right:4px" @click="handleImageSelect">
          <img style="height:14px;width:14px" src='statics/icons/app/iconmore.png'>
        </span>
      </template>
    </div>
  </div>
</template>
<script>
import { SysMLUtilHelper } from 'src/api/sysml-imports';
import { escape2Html, chooseFile, parseToBase64 } from "src/util/common";
import { PropertyUtil } from './PropertyUtil';
import SimpleInput from './SimpleInput';
import CompoundedInput from './CompoundedInput';
import { selectValue } from './../modals/SelectValue';
import { selectMutiple } from './../modals/SelectMutiple';
import { selectProperty } from './../modals/SelectProperty';
import globalConfig from 'src/util/Global';
import { LocalFileElectron } from 'src/util/localFile/LocalFileElectron';
import { LocalFileService } from 'src/util/localFile/LocalFileService';
import { propertyFactory } from '../config/PropertyFactory';
import { graphHelper } from '@/api/GraphHelper';
import { actions } from 'src/pages/mxgraph/Actions.ts';

const plainTypes = ['input', 'textarea', 'switch', 'single-select', 'muti-seelct', 'compounded-input'];

export default {
  name: 'attr-list-property',
  components: {
    'm-simple-input': SimpleInput,
    'm-compounded-input': CompoundedInput,
  },
  props: {
    graphNode: Object,
    property: Object,
    selectedRowId: String,
    isPropertyGroup: { //// 用于控制在属性分组中的显示效果
      type: Boolean,
      default: false
    },
    largeType: Boolean,
  },
  data() {

    //// editType: input textarea radio  single-select muti-select object-single-select object-muti-select
    //// allowCustom: Boolean
    //// customEditType: as same as editType
    //// filterCondition:'Package' / 'Package,Model'
    /**
           * 普通输入框：input  1
            长文本输入框：textarea 1
            富文本：rich-textarea
            开关：switch
            普通下拉单选：single-select
            普通下拉多选： muti-select
            对象树型单选：tree-single-select 1
            对象树形多选：tree-muti-select 1
            对象下拉单选：drop-single-select
            对象下拉多选：drop-muti-select
            混合输入框：compounded-input 类型切换的输入框
            多行输入框：muti-row-input
           */
    return {
      valueForEdit: '',
      valuesForEdit: [],
      mutiRowInputValues: [],
      imageURL: ''
    };
  },
  computed: {
    selected(){
      return this.isPropertyGroup ? this.selectedRowId === this.graphNode.id +  this.config.key : this.selectedRowId === this.config.key;
    },
    config(){
      return this.property.config;
    },
    readonly(){
      return this.graphNode.disabled || this.property.config.readonly;
    },
    values(){
      return [];
    },
    value(){
      return PropertyUtil.getNodePropertyValue(this.graphNode, this.property);
    },
    type(){
      if (this.config.editType === 'compounded-input') {
        return SysMLUtilHelper.getElementClassName(this.value) || 'LiteralString';
      }
      return null;

    },

    iconPath(){
      //// this.value 在连线的时候 this.value会变成数组？？？
      if (!this.value || !this.value['getTypeName'] ) return '';
      const conf = app.configManager.getTypeNameConfigItem(this.value.getTypeName());
      return conf && conf.icon; //// getImgPath(this.value.getTypeName());
    },
  },
  watch: {
    property: {
      immediate: true,
      handler() {
        PropertyUtil.initPropertyConfig(this.property);
        this.getImageURL();
        this.getMutiRowInputValue();
      }
    },
    value: {
      handler(val){
        this.valueForEdit = this.getValueForEdit();
        if (this.property.config.key === 'Type') { //// 关联类型变化，触发属性栏重载
          this.$emit('rerender');
        }
      }
    },
  },
  created() {
    //// this.getImageURL();
    //// this.getMutiRowInputValue();
    this.valueForEdit = this.getValueForEdit();
  },
  mounted(){
    //// if (this.config.editType === 'input' || this.config.editType === 'textarea') {
    ////   this.valueForEdit = this.value;

    //// }
    //// console.log("valueForEdit", this.valueForEdit);
  },

  methods: {
    getImageURL() {
      if (this.config.editType === 'img') {
        //// console.log('this.property.getValue()', this.property.getValue());
        const value = this.property.getValue().toArray();
        if (value.length > 0) {
          this.imageURL = value[0].content;
        } else {
          this.imageURL = '';
        }
        
      }
    },
    getMutiRowInputValue() {
      if (this.config.editType === 'muti-row-input') {
        const value = this.value && this.value.toArray();
        if (value.length > 0) {
          this.mutiRowInputValues = value;
        } else {
          this.mutiRowInputValues = [];
        }
      }
    },

    getValueForEdit(){
      if (plainTypes.includes(this.config.editType)) {
        return this.value;

      }

    },
    handleFocusRow(event){
      this.$nextTick(() => {
        event.input.select();
      });

    },
    handleSelectRow(){
      this.$emit('select', this.property, this.graphNode);

    },
    handleSaveInput(){
      this.updateRow(this.valueForEdit);

    },
    handleCheckChange(e){
      console.log(e.target.checked);
      //// row.rowData.value = e.target.checked;
      this.updateRow(e.target.checked);

    },
    deleteTreeItem(index) {
      this.value.splice(index, 1);
      this.updateRow(this.value, this.value.map(item => graphHelper.getGraphNodeById(item.id, app.activeProjectId)));
    },
    handleSingleSelect(){
      if (this.inSelect) return;
      this.inSelect = true;
      //// if (row.moreBtnType === 'Select Owner'){
      window.event.stopPropagation();
      selectValue.popup({
        currentId: this.value && this.value.id,
        //// filterCondtion: row.moreBtnCondition
        filterCondtion: this.config.moreBtnCondition,
        propertyKey: this.property.fromStereotype ?  this.property.property : this.property.config.key,
        selectedElement: app.selectedElement.model,
        isRequired: this.property.required
      }).then(res => {
        if (res) {
          this.updateRow(res.graphNode.model, [res.graphNode]);
        } else {
          this.updateRow();
        }

      }).catch(e => {
        if (e){
          throw e;

        }

      }).finally(res => {
        this.inSelect = false;
      });

    },
    handleMultiSelect(){
      if (this.inSelect) return;
      this.inSelect = true;
      window.event.stopPropagation();
      console.log('selectMultiple.popup');
      console.log('property', this.property);
      selectMutiple.popup({
        currentIds: this.value ? this.value.map(i => i.id) : [],
        filterCondtion: this.config.moreBtnCondition,
        propertyKey: this.property.fromStereotype ?  this.property.property : this.property.config.key,
        selectedElement: app.selectedElement.model,
        isRequired: this.required
      }).then(res => {

        console.log(res, 'res');
        const modelArr = res.map(i => i.graphNode.model);
        const graphNodeArr = res.map(i => i.graphNode);
        this.updateRow(modelArr, graphNodeArr);
      }).catch(e => {
        //// e && console.error(e);
        if (e){
          throw e;
        }
      }).finally(() => {
        this.inSelect = false;
      });

    },
    handleSingleSelectChange(value){
      //// row.rowData.value = value;
      this.updateRow(value);

    },
    handleMultiSelectChange(value){
      this.updateRow(value);
    },
    handleCompoundChange(value) {
      this.updateRow(value);
      //// const propertyDefine = propertyFactory.get(this.property.config.key, this.graphNode.getTypeName());
      //// console.log(this.property.config.key);
      //// propertyDefine.setValue(this.graphNode, value);

    },
    updateRow(value, graphNodes) {
      PropertyUtil.updateRow(value, this.property, app.selectedElement, graphNodes);
      const typeName = app.selectedElement.getTypeName();
      if (typeName === 'Instance') {
        app.selectedElement.refreshCompartment();
        if (this.property.config.key === 'Classifier') {
          app.selectedElement.childLeafElement.forEach(shape => {
            actions.getAction('setProperty').setInstanceImage(shape, graphNodes[0]);
          });
        }
      }
      if (typeName.includes('Message')) { //// 改变消息的箭头
        console.log('value', value);
        const shape = app.selectedElement.childLeafElement[0];
        let style = shape.box.style;
        if (value.includes('::synchCall')) { //// 实心箭头
          style = style.replace(/endArrow=.*;/, 'endArrow=classic;endSize=8;');
        } else { //// 空心箭头
          style = style.replace(/endArrow=.*;/, 'endArrow=open;endSize=8;');

        }
        shape.box.style = style;
      }
      this.$bus.emit('model-update', { id: app.selectedElement.model.id });
      //// if (this.property.config.key === 'Name'){

      //// this.graphNode.childLeafElement.forEach(shape => {
      ////   const mainShape = GraphShapeUtil.getAbsoluteMainShape(shape);

      ////   resizeUtil.updateAutoFlow(mainShape);

      //// });

      //// }
      ////  else if (this.property.property && this.property.property.name === 'direction') {
      ////   this.graphNode.childLeafElement.forEach(shape => {
      ////     const styleObj = getStyleObj( shape.box.style);
      ////     styleObj.arrowType = 'in'; //// out / inout / none
      ////     shape.box.style = getStyleStr(styleObj);

      ////     resizeUtil.updateAutoFlow(shape);

      ////   });
      //// }
      //// this.$bus.emit("fresh-graph");

    },
    handleMultiRowInputChange(value, index) {
      const currentValue = this.mutiRowInputValues[index];
      this.$set(this.mutiRowInputValues, index, value);
    },
    handleMultiRowFocusRow(event, index){

    },
    handleMultiRowSaveInput(index){
      this.updateRow([...this.mutiRowInputValues]);
    },
    handleMultiRowDelete(index){
      this.mutiRowInputValues.splice(index, 1);
      this.handleMultiRowSaveInput();
    },
    handlePopMultiRowInput(){
      //// window.event.clientX;
      //// textModal.popup({ text: '', x: window.event.clientX, y: window.event.clientY }).then(res => {
      ////   console.log(res);
      //// });
      this.mutiRowInputValues.push('');
    },

    handleMultiRowTextDelete(index){
      PropertyUtil.updateRow([], this.property, this.graphNode);
      this.$bus.emit('model-update', { id: app.selectedElement.model.id });
    },
    handlePopMultiRowText(){
      window.event.stopPropagation();
      let dataList;
      let type = 'radio';
      const config = this.property.config;
      if (config.name === 'properties') {
        type = 'radio';
        dataList = SysMLUtilHelper.getPropertyByCustomizationTarget(this.graphNode);
      } else if (config.name === 'columns') {
        type = 'checkbox';
        dataList = SysMLUtilHelper.getColumnByCustomizationTarget(this.graphNode);
      }
      console.log(config);
      selectProperty.popup({ dataList, type, graphNode: this.graphNode, selectedItemKeys: this.value ? this.value.toArray() : [] }, { single: true })
        .then(res => {
          const { selectedItem, checkItem } = res;
          console.log(res, );
          if (type === 'radio') {
            const properties = this.graphNode.properties.toArray();  //// graphProperty;
            let columnsProperty = properties.find(p => p.config.name === 'columns');
            const lastValue = this.value && this.value.toArray()[0];
            PropertyUtil.updateRow(selectedItem.name, this.property, this.graphNode);
            if (lastValue !== selectedItem.name) {
              PropertyUtil.updateRow([], columnsProperty, this.graphNode); //// 清除colums数据
            }
          } else if (type === 'checkbox') {
            PropertyUtil.updateRow(checkItem, this.property, this.graphNode);
          }
          this.$bus.emit('model-update', { id: app.selectedElement.model.id });
        })
        .catch(err => console.log(err));
      
    },
    getIconPath(model){
      if (!model) return '';
      const conf = app.configManager.getTypeNameConfigItem(model.getTypeName());
      return conf && conf.icon;
    },
    getDisplayText(model){
      if (model.typeName === 'Slot') {
        return escape2Html(graphHelper.getGraphNodeById(model.id, app.activeProjectId).displayTitle);
      }
      if (model.getDisplayName) {
        return escape2Html(model.getDisplayName());
      } else {
        console.error('model.getDisplayName', this, model, '-------------');
        return '';
      }

    },
    log(str){
      console.log(str);
    },

    //// 选择图片
    async handleImageSelect() {
      let fileData = {};
      if (globalConfig.isElectron) {
        const fileElectron = new LocalFileElectron();
        const filePath = fileElectron.showOpenDialog({
          title: '选择图片',
          buttonLabel: "确定",
          filters: [{ name: '图片文件', extensions: ['jpg', 'png', 'gif'] }]
        });
        if (!filePath) return;
        fileData.data = await LocalFileService.readFile(filePath);
        if (fileData.data.length > 50000){
          app.$messageBox.error({
            id: 110,
            text: '上传失败：上传图片限制50Kb'
          });
          return;
        }
        fileData.name = filePath.split('\\').pop();
      } else {
        fileData = await chooseFile('image/*');
      }
      const base64String = parseToBase64(fileData.data, fileData.name);
      this.imageURL = base64String;     
      this.updateRow(base64String);
    }

  }
};
</script>
<style lang="scss">
.v-attribute-list-property {
  ._textarea {
    border-left:1px solid #E4E3E3;
    border-bottom:1px solid #E4E3E3;
    &:first-of-type {
      border-top:1px solid #E4E3E3;
    }
  }
  .tree-muti-select-box {
    display: flex;
    align-items: center;
    .delete-btn {
      display: none;
    }
    &:hover {
      .delete-btn {
        display: inline-block;
      }
    }
  }
}
</style>
